package com.kady.controller;

import com.alibaba.druid.util.StringUtils;
import com.kady.contant.MessageConstant;
import com.kady.entity.ResultVO;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: kady
 * \* Date: 2021/3/24
 * \* Time: 17:39
 * \* 千峰JAVA2101班
 * \* Description: serlevt公共类
 * \
 */
public class BaseServlet extends HttpServlet {

    /**
     *
     * 所有请求都要通过servlet的service方法来处理，抽取公共部分
     */

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            String method_name = req.getParameter(MessageConstant.METHOD_STRING);
            /**
             * 反射创建对象
             */
            Class clazz = this.getClass();
            /**
             * 通过反射创建的对象使用方法名获取方法
             */
            Method method = clazz.getMethod(method_name,HttpServletRequest.class,HttpServletResponse.class);
            /**
             * 执行获取到的方法
             */
            Object obj = method.invoke(this,req,resp);

            if(obj!=null && obj instanceof String){
                String result = (String) obj;
                String url = result.substring(result.indexOf(MessageConstant.INTERRUPTER) + 1);
                if(result.startsWith(MessageConstant.PREFIX_FORWARD)){
                    req.getRequestDispatcher(url).forward(req,resp);
                }else if(result.startsWith(MessageConstant.PREFIX_REDIRECT)){
                    resp.sendRedirect(url);
                }else{
                    resp.getWriter().write(result);
                }
            }
            if(obj!=null && obj instanceof ResultVO){
                resp.getWriter().write("<script>alert('" + ((ResultVO)obj).getMessage() +"');window.history.go(-1);</script>");
            }
            return;
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        resp.getWriter().write(MessageConstant.COMMON_ERROR_MESSAGE);
    }
}
